package com.olda.play.auth.service.impl;

import cn.hutool.json.JSONUtil;
import com.olda.play.auth.service.AuthService;
import com.olda.play.constant.Constant;
import com.olda.play.request.RequestUtils;
import com.olda.play.rpc.CommonResponseDto;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.Map;

@Service
@RestController
@RequestMapping("/oauth")
@Slf4j
@AllArgsConstructor
public class AuthServiceImpl implements AuthService {

    private TokenEndpoint tokenEndpoint;


    @RequestMapping(value = "/getAuthToken",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    @ResponseBody
    @Override
    public CommonResponseDto<String> getAuthToken(@RequestParam  String username) {
        return CommonResponseDto.success(username);
    }

    @RequestMapping(value = "/getAuthToken1",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    @ResponseBody
    @Override
    public CommonResponseDto<String> getAuthToken1(@RequestParam  String username) {
        return CommonResponseDto.success(username);
    }


    @RequestMapping(value = "/token")
    @Override
    public Object postAccessToken(
            Principal principal,
            @RequestParam Map<String, String> parameters
    ) throws HttpRequestMethodNotSupportedException {
        /**
         * 获取登录认证的客户端ID
         *
         * 兼容两种方式获取Oauth2客户端信息（client_id、client_secret）
         * 方式一：client_id、client_secret放在请求路径中(注：当前版本已废弃)
         * 方式二：放在请求头（Request Headers）中的Authorization字段，且经过加密，例如 Basic Y2xpZW50OnNlY3JldA== 明文等于 client:secret
         */
        String clientId = RequestUtils.getOAuth2ClientId();
        log.info("OAuth认证授权 客户端ID:{}，请求参数：{}", clientId, JSONUtil.toJsonStr(parameters));

        /**
         * knife4j接口文档测试使用
         *
         * 请求头自动填充，token必须原生返回，不能有任何包装，否则显示 undefined undefined
         * 账号/密码:  client_id/client_secret : client/123456
         */
        if (Constant.TEST_CLIENT_ID.equals(clientId)) {
            return tokenEndpoint.postAccessToken(principal, parameters).getBody();
        }
        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        return CommonResponseDto.success(accessToken);
    }
}
